package com.yhxd.modular.institutions.service;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.yhxd.modular.institutions.dao.DeptDao;
import com.yhxd.modular.institutions.entity.Dept;
import com.yhxd.modular.institutions.entity.QDept;
import com.yhxd.modular.news.dao.MyInfoDao;
import com.yhxd.modular.news.entity.QNews;
import com.yhxd.modular.system.entity.User;
import com.yhxd.modular.system.vo.ResultVo;
import com.yhxd.utils.QueryDslUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 机构业务实现类
 *
 * @author lzl
 * @date 2020/12/22 16:30
 */
@Service
public class DeptService {

    @Autowired
    private JPAQueryFactory factory;

    @Autowired
    private DeptDao deptDao;
    @Autowired
    private MyInfoDao myInfoDao;

    /**
     * 获取搜索的部门
     *
     * @return
     */
    public List<Dept> findAll() {
        return this.deptDao.findAll();
    }

    /**
     * 分页查询机构信息
     *
     * @param pageRequest
     * @param dto
     * @return
     */
    public Page<Dept> findList(QPageRequest pageRequest, Dept dto) {
        QDept qDept = QDept.dept;

        Predicate where = qDept.id.isNotNull();
        if (ObjectUtils.isNotEmpty(dto.getDepName())) {      //部门名称
            where = ExpressionUtils.and(where, qDept.depName.like("%" + dto.getDepName() + "%"));
        }
        if (ObjectUtils.isNotEmpty(dto.getExternal())) {      //是否外部机构
            where = ExpressionUtils.and(where, qDept.external.eq(dto.getExternal()));
        }
        if (ObjectUtils.isNotEmpty(dto.getDepType())) {      //机构类型
            where = ExpressionUtils.and(where, qDept.depType.eq(dto.getDepType()));
        }
        if (ObjectUtils.isNotEmpty(dto.getManagerDep())) {      //主管单位
            where = ExpressionUtils.and(where, qDept.managerDep.eq(dto.getManagerDep()));
        }
        if (ObjectUtils.isNotEmpty(dto.getPname())) {      //父机构
            where = ExpressionUtils.and(where, qDept.pname.like("%" + dto.getPname() + "%"));
        }
        if (ObjectUtils.isNotEmpty(dto.getRespName())) {      //负责人
            where = ExpressionUtils.and(where, qDept.respName.like("%" + dto.getRespName() + "%"));
        }
        if (ObjectUtils.isNotEmpty(dto.getRespPhone())) {      //负责人电话
            where = ExpressionUtils.and(where, qDept.respPhone.like("%" + dto.getRespPhone() + "%"));
        }
        if (ObjectUtils.isNotEmpty(dto.getLinkName())) {      //联系人
            where = ExpressionUtils.and(where, qDept.linkName.like("%" + dto.getLinkName() + "%"));
        }
        if (ObjectUtils.isNotEmpty(dto.getLinkPhone())) {      //联系人电话
            where = ExpressionUtils.and(where, qDept.linkPhone.like("%" + dto.getLinkPhone() + "%"));
        }
        QueryResults<Dept> deptList = this.factory
                .selectFrom(qDept)
                .where(where)
                .orderBy(QueryDslUtils.getOrderSpecifier(pageRequest.getSort()))
                .offset(pageRequest.getOffset())
                .limit(pageRequest.getPageSize())
                .fetchResults();
        Page<Dept> deptPage = new PageImpl<>(deptList.getResults(), pageRequest, deptList.getTotal());
        return deptPage;
    }

    /**
     * 添加或修改部门信息
     *
     * @param dept
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo saveOrUpdate(Dept dept) {
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Date date = new Date();
        if (null == dept.getId()) {
            dept.setCreateName(user.getRealName());
            dept.setCreateTime(date);
            this.deptDao.save(dept);
            return ResultVo.success(null);
        } else {
            Dept dept1 = this.deptDao.findById(dept.getId()).orElse(null);
            if (dept1 != null) {
                dept1.setUpdateName(user.getRealName());
                dept1.setUpdateTime(date);
                dept1.setDepName(dept.getDepName());
                dept1.setExternal(dept.getExternal());
                dept1.setDepType(dept.getDepType());
                dept1.setManagerDep(dept.getManagerDep());
                dept1.setPid(dept.getPid());
                dept1.setPname(dept.getPname());
                dept1.setSort(dept.getSort());
                dept1.setRespName(dept.getRespName());
                dept1.setRespPhone(dept.getRespPhone());
                dept1.setLinkName(dept.getLinkName());
                dept1.setLinkPhone(dept.getLinkPhone());
                dept1.setZipcode(dept.getZipcode());
                dept1.setAddress(dept.getAddress());
                this.deptDao.save(dept1);
                return ResultVo.success(null);
            } else {
                return ResultVo.error("修改部门不存在");
            }
        }
    }

    /**
     * 通过id获取部门信息
     *
     * @param id
     */
    public Dept findById(Long id) {
        return this.deptDao.findById(id).orElse(new Dept());
    }

    /**
     * 通过id删除部门信息
     *
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        QDept qDept = QDept.dept;
        this.factory
                .delete(qDept)
                .where(qDept.id.eq(id))
                .execute();
    }

    /**
     * 修改部门启用状态
     *
     * @param dept
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo updateStatus(Dept dept) {
        Dept dept1 = this.deptDao.findById(dept.getId()).orElse(null);
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        if (dept1 != null) {
            QDept qDept = QDept.dept;
            this.factory
                    .update(qDept)
                    .set(qDept.enable, dept.getEnable())
                    .set(qDept.updateName, user.getRealName())
                    .set(qDept.updateTime, new Date())
                    .execute();
            return ResultVo.success(null);
        } else {
            return ResultVo.error("修改部门不存在");
        }
    }

    /**
     * 判断部门下面是否有新闻
     *
     * @param id
     */
    public Boolean isRelateNews(Long id) {
        QDept qDept = QDept.dept;
        QNews qNews = QNews.news;

        Long count = this.factory
                .select(qNews.count())
                .from(qNews)
                .leftJoin(qDept)
                .on(qNews.deptId.eq(qDept.id))
                .where(qNews.deptId.eq(id))
                .fetchOne();
        if (count > 0) {
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}
